<template>
  <div class="date-slider">
    <el-form-item label="阶段周期" >
      <el-date-picker style="width: 240px" v-model="valueStateRange" @change="stageRangeSet" type="daterange"
                      value-format="yyyy-MM-dd" range-separator="至" :clearable="false"
                      size="mini" start-placeholder="开始日期" end-placeholder="结束日期">
      </el-date-picker>
    </el-form-item>
    <div id="lineDiv" class="lineDiv">
      <div class="minDiv" :class="'minDiv'+index" v-for="(item,index) in step" :id="index == currentMove ? 'minDiv' : ''" @mousedown="starts($event,index)" :data-x="item.pos">
      </div>
      <div class="steps" >
        <div class="boxs" v-for="(item,index) in stepBox" :id="'minDivs'+index">
          <span>{{stageFour[index]}}</span>
           <div>{{item.date}}</div>
        </div>
        <div class="startD">{{startDate}}</div>
      </div>
    </div>
  </div>
</template>

<script>
  import * as opreate from 'api/getData'
  let mUtilDate = new Date().getFullYear()

  export default {
    name: "date-slider",
    data() {
      return {
        ifBool:false,
        step:[{pos:'10'},{pos:'20'},{pos:'30'}],
        currentMove:10,
        lineDiv:'',
        vals:0,
        currend:'',
        stepBox:[{date:`${mUtilDate}-03-01`},{date:`${mUtilDate}-06-01`},{date:`${mUtilDate}-09-01`},{date: `${mUtilDate}-12-01`}],
        minDiv:'',
        totalDays:50,
        className:'',
        startDate: `${mUtilDate}-01-01`,
        myDateSet:'',
        endDate:'',
        lineDiv_left:'',
        valueStateRange:[],
        setRange:{},
        stageFour:['试销','预热','高潮','持续']
      }
    },
    props:{
      contState:{
        type:Object,
        default:() => {}
      },
      productId:{
        type:String,
        default:1
      }
    },
    mounted() {
      this.setStage()
      this.lineDiv = document.getElementById('lineDiv'); //长线条
      this.lineDiv_left = this.getPosition(this.lineDiv).left//长线条的横坐标
      window.addEventListener("touchmove", this.mouseMove);
      window.addEventListener("mousemove", this.mouseMove);
      window.addEventListener("touchend", this.mouseEnd); //鼠标松开
      window.addEventListener("mouseup", this.mouseEnd);
    },
    methods: {
      setStageList(paramSet, startTime, endTime){
        this.setRange.startTime = startTime
        this.setRange.endTime = endTime
        this.setRange.stageList = paramSet.map((item,index) => {
          return { stageId: item.stageId, startTime: index == 0 ? this.startDate : paramSet[index-1].date, endTime:item.date, stageName:this.stageFour[index] }
        })
      },
      setStage(){
        opreate.getStage({ productId: this.productId }).then(res => {
          let tempSet = res.data || {}
          let { startTime = null, endTime = null, stageList = [] } = tempSet || {}
          this.startDate = startTime ? startTime : `${mUtilDate}-01-01`
          this.valueStateRange = [ startTime || `${mUtilDate}-01-01`, endTime || this.stepBox[3].date]
          this.setRange = tempSet
          if(stageList.length > 0){  //已对该品类进行阶段设置
            (startTime && endTime) ? this.stepBox = stageList.map(item => {
              return { date: item.endTime, stageId: item.stageId }
            }) : ''
            this.setStageList(this.stepBox, ...this.valueStateRange)
            this.$emit('update:contState', this.setRange)
          }else { //未对该品类进行阶段设置
            this.setStageList(this.stepBox, ...this.valueStateRange)
            this.$emit('update:contState', this.setRange)
          }
          this.initState(...this.valueStateRange)
        })
      },
      stageRangeSet(){
        let [ startTime = null, endTime = null ] = this.valueStateRange
        this.startDate = startTime ? startTime : new Date().format('yyyy-MM-dd')
        let startTimeSet = startTime ? new Date(startTime.replace('-','/')) : new Date()
        let yearSet = startTimeSet.format('yyyy-MM')
        let dateSet = startTimeSet.format('dd')
        this.stepBox = [{date: yearSet+'-'+(Number(dateSet)+1)},{date: yearSet+'-'+(Number(dateSet)+2)},{date: yearSet+'-'+(Number(dateSet)+3)},{date: endTime || `${mUtilDate}-12-01`}]
        this.initState(...this.valueStateRange)
      },
      /**
       * @desc: This is Note
       * @author: coulis
       * 获取时间差，计算百分比，确定滑块的位置和面积
       * @date: 2018/10/25 20:02:10
       **/
      initState(startDate, endDateSet){
        this.myDateSet = new Date(startDate.replace(/-/g, "/"))
        this.endDate = new Date(endDateSet.replace(/-/g, "/"))
        let diffVal = this.endDate.valueOf() - this.myDateSet.valueOf();
        this.totalDays = diffVal = parseInt(diffVal/(1000*60*60*24))
        this.stepBox.map((item,index) => {
          if(index < this.stepBox.length-1){
            let days = new Date(item.date.replace(/-/g, "/")).valueOf() - this.myDateSet.valueOf()
            days = parseInt(days/(1000*60*60*24))
            this.step[index].pos = days
            document.querySelector('.minDiv'+ index).style.left = Math.ceil(days/this.totalDays*(this.lineDiv.offsetWidth - 12) )+ 'px'
            let currWidth = Math.ceil(days/this.totalDays*(this.lineDiv.offsetWidth - 12) )+6
            currWidth = currWidth >= 400 ? (index + 1)*100 : currWidth
            document.getElementById('minDivs'+ index).style.width = currWidth + "px"
          }else {
            document.getElementById('minDivs'+ index).style.width = 400 + "px"
          }
        })
      },
      starts(e,index){
        this.currentMove = index
        this.className = 'minDivs'+ index
        e.stopPropagation();
        this.ifBool = true;
      },
      mouseMove(e){
        if(this.ifBool) { // e.touches://兼容PC端OR//兼容移动端
          let x = e.touches ? e.touches[0].pageX : e.clientX;
          this.minDiv = document.getElementById('minDiv');
          let minDiv_left = x - this.lineDiv_left; //小方块相对于父元素（长线条）的left值
          let percent = parseInt((minDiv_left/(lineDiv.offsetWidth - 12)) * this.totalDays)
          this.minDiv.setAttribute('data-x',percent)
          let nextX,prevX
          /**
           * @desc: This is Note
           * @author: coulis
           * 判断滑块位置，限定滑动范围
           * @date: 2018/10/25 20:06:23
           **/
          if(this.minDiv.nextElementSibling.getAttribute('data-x') && this.minDiv.nextElementSibling.getAttribute('data-x') != null){
            nextX = this.minDiv.nextElementSibling.getAttribute('data-x')
            if(percent >= Number(nextX -1)) {
              percent = Number(nextX -1)
              this.minDiv.setAttribute('data-x',percent)
              minDiv_left = percent/this.totalDays*(lineDiv.offsetWidth - 12)
            }else {
              this.minDiv.setAttribute('data-x',percent)
            }
          }else {
            if(percent >= this.totalDays -1 ) {
              minDiv_left = this.lineDiv.offsetWidth - 12;
              percent = this.totalDays -1
              this.minDiv.setAttribute('data-x',percent)
            }
          }
          if(this.minDiv.previousElementSibling){
              prevX = this.minDiv.previousElementSibling.getAttribute('data-x')
              if(percent <= Number(prevX)+1){
                percent =  Number(prevX)+1
                this.minDiv.setAttribute('data-x',percent)
                minDiv_left = percent/this.totalDays*(lineDiv.offsetWidth - 12)
              }else {
                this.minDiv.setAttribute('data-x',percent)
              }
          }else {
            if(minDiv_left < 0) {
              minDiv_left = 0;
              percent = 1
              this.minDiv.setAttribute('data-x',percent)
            }
          }

          //设置拖动后小方块的left值
          this.minDiv.style.left = Math.ceil(minDiv_left) + "px";
          let fontWidth = Math.ceil(minDiv_left)+6
          document.getElementById(this.className).style.width = fontWidth + "px"
          if(this.currentMove > 0){
            document.getElementById(this.className).firstElementChild.style.width = fontWidth - document.getElementById('minDivs'+ (this.currentMove-1)).style.width.replace('px','') + "px"
          }else {
            document.getElementById(this.className).firstElementChild.style.width = fontWidth + 'px'
          }
          document.getElementById('minDivs'+ (this.currentMove+1)).firstElementChild.style.width =  document.getElementById('minDivs'+ (this.currentMove+1)).style.width.replace('px','')-fontWidth  + "px"
          this.myDateSet = new Date(this.startDate.replace(/-/g, "/"))
          this.myDateSet.setDate(this.myDateSet.getDate()+percent)
          this.stepBox[this.className.replace('minDivs','')].date = this.myDateSet.format('yyyy-MM-dd')
          this.vals = percent
          this.setStageList(this.stepBox, ...this.valueStateRange)
        }
      },
      mouseEnd(){
        this.ifBool = false
        this.currentMove = 10
        this.$emit('update:contState', this.setRange)
      },
      getPosition(node){
        let left = node.offsetLeft; //获取元素相对于其父元素的left值var left
        let top = node.offsetTop;
        this.currend = node.offsetParent; // 取得元素的offsetParent

        while(this.currend != null) { // 一直循环直到根元素
          left += this.currend.offsetLeft;
          top += this.currend.offsetTop;
          this.currend = this.currend.offsetParent;
        }
        return { left, top }; //获取直线left值
      }
    }
  }
</script>

<style scoped>
  .lineDiv {
    position: relative;
    height: 1px;
    background: red;
    width: 400px;
    margin: 75px auto;
    margin-top: 10px;
  }

  .lineDiv .minDiv0 {
    position: absolute;
    top: -5px;
    left: 94px;
    cursor: pointer;
    width: 0px;
    height: 0px;
    border-top: 6px solid #c6d2dd;
    border-left: 6px solid transparent;
    border-right: 6px solid transparent;
    border-bottom: 6px solid transparent;
  }
  .steps{
    width: 400px;
    height: 40px;
    background: #66b1ff;
    white-space: normal;
    position: relative;
  }
  .steps .boxs{
    width: 25%;
    height: 40px;
    display: inline-block;
    position: absolute;
    left: 0;
    text-align: right;
  }
  .steps .boxs:first-child{
    background: #64bef5;
    width: 100px;
    z-index: 99;
  }
  .steps .boxs:nth-child(2){
    background: #9c96e7;
    width: 200px;
    z-index: 88;
  }
  .steps .boxs:nth-child(3){
    background: #fd859a;
    width: 300px;
    z-index: 77;
  }
  .steps .boxs:nth-child(4){
    background: #64bef5;
    width: 400px;
  }
  .boxs div{
    position: absolute;
    right: -30px;
    font-size: 12px;
    color: #999;
    bottom: -18px;
  }
  .boxs span{
    color: #ffffff;
    font-size: 12px;
    line-height: 40px;
    display: inline-block;
    text-align: center;
  }
  .steps .boxs:first-child span{
    width: 69px;
  }
  .steps .boxs:nth-child(2) span{
    width: 98px;
  }
  .steps .boxs:nth-child(3) span{
    width: 99px;
  }
  .steps .boxs:nth-child(4) span{
    width: 134px;
  }
  .steps .startD{
    position: absolute;
    left: -30px;
    font-size: 12px;
    color: #999;
    bottom: -18px;
  }
  .lineDiv .minDiv1 {
    position: absolute;
    top: -5px;
    left: 194px;
    width: 0px;
    height: 0px;
    border-top: 6px solid #c6d2dd;
    border-left: 6px solid transparent;
    border-right: 6px solid transparent;
    border-bottom: 6px solid transparent;
    cursor: pointer
  }
  .lineDiv .minDiv2 {
    position: absolute;
    top: -5px;
    left: 296px;
    width: 0px;
    height: 0px;
    border-top: 6px solid #c6d2dd;
    border-left: 6px solid transparent;
    border-right: 6px solid transparent;
    border-bottom: 6px solid transparent;
    cursor: pointer
  }

  .lineDiv .minDiv .vals {
    position: absolute;
    font-size: 20px;
    top: -45px;
    left: -10px;
    width: 35px;
    height: 35px;
    line-height: 35px;
    text-align: center;
    background: #c6d2dd;
  }

  .lineDiv .minDiv .vals:after {
    content: "";
    width: 0px;
    height: 0px;
    border-top: 6px solid #c6d2dd;
    border-left: 6px solid transparent;
    border-right: 6px solid transparent;
    border-bottom: 6px solid transparent;
    display: block;
    margin-left: 11px;
  }
</style>
